package com.lz.route;

import com.lz.handler.HelloHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.reactive.config.EnableWebFlux;
import org.springframework.web.reactive.function.server.RouterFunction;
import org.springframework.web.reactive.function.server.ServerResponse;

import static org.springframework.http.HttpStatus.UNAUTHORIZED;
import static org.springframework.http.MediaType.APPLICATION_JSON;
import static org.springframework.web.reactive.function.server.RequestPredicates.accept;
import static org.springframework.web.reactive.function.server.RouterFunctions.route;

/**
 * @Title: HelloRouter
 * @ClassName: com.lz.route.HelloRouter.java
 * @Description: Person获取
 *
 * @Author by: li
 * @Date: 2019/1/9 14:07
 * @Version: V1.0
 */
@Configuration
@EnableWebFlux
public class Router {
    @Value("${user.name}")
    private String name;

    @Value("${user.pass}")
    private String pass;
    @Autowired
    private HelloHandler handler;
    private SecurityManager securityManager = new SecurityManager();

    /*
    @Bean
    public RouterFunction personRoute() {
        RouterFunction<ServerResponse> route = route()
                .GET("/person/{id}", accept(MediaType.ALL), handler::getPerson)
                .GET("/person", accept(APPLICATION_JSON), handler::listPeople)
                .POST("/person", handler::createPerson)
                .build();
        return route;
    }
    */

    @Bean
    public RouterFunction securityFunction() {
        RouterFunction<ServerResponse> route = route()
                .path("/person", b1 -> b1.nest(accept(APPLICATION_JSON),
                                b2 -> b2
                                // .GET("/{id}", handler::getPerson)
                                .GET("", handler::listPeople))
                        .POST("/person", handler::createPerson))
                .filter((request, next) -> {
                    if (isLogin((String) request.queryParam("name").get(), (String) request.queryParam("pass").get())) {
                        return next.handle(request);
                    } else {
                        return ServerResponse.status(UNAUTHORIZED).build();
                    }
                })
                .build();
        return route;
    }

    private boolean isLogin(String name, String pass) {
        if (this.name.equals(name) && this.pass.equals(pass)) {
            return true;
        }
        return false;
    }
}
